﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

using mvcForum.Core;
using mvcForum.Core.Interfaces.Data;

using mvcForum.Web.Controllers;
using mvcForum.Web.Extensions;

using TopicVM = mvcForum.Web.Areas.ForumAPI.ViewModels.Topic;
using PostLight = mvcForum.Web.Areas.ForumAPI.ViewModels.PostLight;
using mvcForum.Core.Abstractions.Interfaces;

namespace mvcForum.Web.Areas.ForumAPI.Controllers {

	public class TopicController : BaseAPIController {
		private readonly IPostRepository postRepo;
		private readonly IConfiguration config;

		public TopicController(IPostRepository postRepo, IConfiguration config)
			: base() {

			this.postRepo = postRepo;
			this.config = config;
		}

		public ActionResult Read(Int32 id, String mode) {
			Topic topic = this.GetRepository<Topic>().Read(id);
			if (!topic.Forum.HasAccess(AccessFlag.Read)) {
				return new HttpStatusCodeResult(403, "Access is denied");
			}
			TopicVM model = new TopicVM { Id = topic.Id, Title = topic.Title, Author = topic.AuthorName, AuthorId = topic.Author.Id, Flag = topic.Flag, Type = topic.Type, PostCount = topic.PostCount, ViewCount = topic.ViewCount, Posted = topic.Posted, LastPosted = topic.LastPosted, AuthorApiUrl = Url.Action("read", "user", new { mode = "json", area = "forumapi", id = topic.Author.Id }) };
			if (topic.LastPost != null) {
				model.LastPostAuthor = topic.LastPostUsername;
				model.LastPostAuthorId = topic.LastPostAuthor.Id;
				model.LastPostAuthorApiUrl = Url.Action("read", "user", new { mode = "json", area = "forumapi", id = model.LastPostAuthorId });
			}

			return this.CustomJson(model);
		}

		public ActionResult List(Int32 id, String mode, Int32? page) {
			Topic topic = this.GetRepository<Topic>().Read(id);
			if (!topic.Forum.HasAccess(AccessFlag.Read)) {
				return new HttpStatusCodeResult(403, "Access is denied");
			}

			// Is the user a moderator?
			Boolean isModerator = topic.Forum.HasAccess(AccessFlag.Moderator);
			//IList<Post> posts = this.postRepo.ReadPosts(topic, (page.HasValue ? page.Value : 1), this.ActiveUser, isModerator);
			IEnumerable<Post> posts = this.postRepo.Read(this.ActiveUser, topic, (page.HasValue ? page.Value : 1), this.config.MessagesPerPage, this.config.ShowDeletedMessages);

			return this.CustomJson(new {
				Posts = posts.Select(p => new PostLight {
					Id = p.Id,
					Subject = p.Subject,
					Flag = p.Flag,
					Posted = p.Posted,
					Position = p.Position,
					ApiUrl = Url.Action("read", "post", new { mode = "json", area = "forumapi", id = p.Id })
				})
			});
		}
	}
}